﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZMCA.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;

namespace Baosight.ZNH.ZMCA.UI
{
    public partial class ZMCA41 : EFView
    {
        private const int fontSizeNumber = 14;
        public ZMCA41()
        {
            InitializeComponent();
            InitFontSize();

            this.Loaded+=new RoutedEventHandler(ZMCA41_Loaded);
        }

        private void InitFontSize()
        {
            mainConfigRegion.FontSize = fontSizeNumber;
            produceProblemText.FontSize = fontSizeNumber + 2;
            produceProblemType.FontSize = fontSizeNumber;
            produceProblemLevel.FontSize = fontSizeNumber;
            securityRiskText.FontSize = fontSizeNumber + 2;
            riskClassify.FontSize = fontSizeNumber;
            riskLevel.FontSize = fontSizeNumber;
            ternatedeRegulationText.FontSize = fontSizeNumber + 2;
            ternatedeClassify.FontSize = fontSizeNumber;
            ternatedeSource.FontSize = fontSizeNumber;

            manageConfigRegion.FontSize = fontSizeNumber;
            resgGrid.FontSize = fontSizeNumber;
            resgGridAdd.FontSize = fontSizeNumber;
            SaveButton.FontSize = fontSizeNumber;
        }
        //先进行控件的初始化过程，然后再根据用户信息对进行控件赋值
        private void ZMCA41_Loaded(object sender, RoutedEventArgs e)
        { 
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA41");
            eiInfo.Set("method", "initLoad");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, onInitLoadCompleted);

            return;
        }

        private void onInitLoadCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() == -1)
            {
                EFWindow.Alert("数据加载失败！");
                return;
            }
            else
            {


                EIBlock block = e.EIInfo.GetBlock("result");
                produceGroup1.ColumnNumber = 4;
                produceGroup2.ColumnNumber = 4;
                securityTrapGroup1.ColumnNumber = 4;
                securityTrapGroup2.ColumnNumber = 4;
                securityDisobeyGroup1.ColumnNumber = 4;
                securityDisobeyGroup2.ColumnNumber = 4;
                bindToCheckboxGroup(block, produceGroup1, "cmes.cp.problemType");
                //bindToCheckboxGroup(block, produceGroup1, "cmes.ca.manageIndexConfig");
                bindToCheckboxGroup(block, produceGroup2, "cmes.cp.problemLevel");
                bindToCheckboxGroup(block, securityTrapGroup1, "cmes.cl.riskClassify");
                bindToCheckboxGroup(block, securityTrapGroup2, "cmes.cl.riskLevel");
                bindToCheckboxGroup(block, securityDisobeyGroup1, "cmes.cl.classify");
                bindToCheckboxGroup(block, securityDisobeyGroup2, "cmes.cl.sourceClassify");

                EIBlock userBlock = e.EIInfo.GetBlock("userInfo");
                produceGroup1.CheckItems(userBlock.GetRows());
                produceGroup2.CheckItems(userBlock.GetRows());
                securityTrapGroup1.CheckItems(userBlock.GetRows());
                securityTrapGroup2.CheckItems(userBlock.GetRows());
                securityDisobeyGroup1.CheckItems(userBlock.GetRows());
                securityDisobeyGroup2.CheckItems(userBlock.GetRows());
            }
            this.resgGrid.UpdateData(e.EIInfo);
            this.resgGridAdd.UpdateData(e.EIInfo);
            return;
        }

        //初始化CheckBoxGroup
        public void bindToCheckboxGroup(EIBlock block, SimpleCheckBoxGroup checkBoxGroup,String strType)
        {
            if (block == null)
                return;
            IList<EIRow> dataList = new List<EIRow>();
            for (int i = 0; i < block.Rows.Count; i++)
            {
                EIRow row = block.GetRow(i);
                String strTemp = null;
                if (row["fdNo"] != null && !row["fdNo"].Equals(""))
                {
                    strTemp = row["fdNo"].ToString();
                    if(strTemp.Equals(strType))
                        dataList.Add(row);
                }
            }
            checkBoxGroup.Init(dataList, "fdDetailsName");

            return;
        }

        private void addResgBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in this.resgGrid.CheckedItems)
            {
                int index = resgGrid.Items.IndexOf(item);
                EIRow row = resgGrid.EIBlock.Rows[index];
                resgGrid.EIBlock.Rows.RemoveAt(index);
                int count = resgGridAdd.Items.Count;
                resgGridAdd.EIBlock.Rows.Insert(count, row);
            }
            return;
            //foreach (var row in this.resgGrid.CheckedEIRows)
            //{
            //    string tempStr = null;
            //    if (row["fdDetailsName"] != null && !row["fdDetailsName"].ToString().Equals(""))
            //    {
            //        tempStr = row["fdDetailsName"].ToString();
            //    }

            //    bool hasAdded = false;
            //    for (int i = 0; i < this.resgGridAdd.EIBlock.Rows.Count; i++)
            //    {
            //        EIRow tempRow = this.resgGridAdd.EIBlock.GetRow(i);
            //        if (tempStr.Equals(tempRow["fdDetailsName"].ToString()))
            //        {
            //            hasAdded = true;
            //        }
            //    }
            //    if (!hasAdded)
            //    {  
            //        this.resgGridAdd.EIBlock.AddRow(row);
            //    }
            //}
        }

        private void removeResgBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in this.resgGridAdd.CheckedItems)
            {
                int index = resgGridAdd.Items.IndexOf(item);
                EIRow row = resgGridAdd.EIBlock.Rows[index];
                resgGridAdd.EIBlock.Rows.RemoveAt(index);
                int count = resgGrid.Items.Count;
                resgGrid.EIBlock.Rows.Insert(count,row);
            }
            return;  
        }

        /*
         * afterIndex前用来标识一条记录移动后的索引位置；
         */
        private void upResgBtn_Click(object sender, RoutedEventArgs e)
        {
            int afterIndex = 0;
            if (resgGridAdd.CheckedItems.Count != 0 && resgGridAdd.Items.IndexOf(resgGridAdd.CheckedItems[0]) == 0)
            {
                afterIndex = 0;
            }
            else
            {
                afterIndex = -1;
            }
            List<string> listChecked = GetCheckedItems();
            int count = resgGridAdd.CheckedItems.Count;
            for (int i = 0; i < count; i++)
            {
                var item = resgGridAdd.CheckedItems[0];
                int originalIndex = resgGridAdd.Items.IndexOf(item);
                if ((originalIndex - afterIndex) > 1)
                {
                    EIRow row = this.resgGridAdd.EIBlock.Rows[originalIndex];
                    this.resgGridAdd.EIBlock.Rows.RemoveAt(originalIndex);
                    this.resgGridAdd.EIBlock.Rows.Insert(originalIndex - 1, row);
                    afterIndex = originalIndex - 1;
                }
                else
                {
                    afterIndex = originalIndex;
                }
            }

            ReCheckItems(listChecked);
            return;
        }
        /*
         * afterIndex前用来标识一条记录移动后的索引位置；
         */
        private void downResgBtn_Click(object sender, RoutedEventArgs e)
        {
            
            int temp = this.resgGridAdd.CheckedItems.Count - 1;
            int afterIndex = 0;
            if (resgGridAdd.CheckedItems.Count != 0 &&
                resgGridAdd.Items.IndexOf(resgGridAdd.CheckedItems[temp]) == this.resgGridAdd.Items.Count - 1)
            {
                afterIndex = this.resgGridAdd.Items.Count - 1;
            }
            else
            {
                afterIndex = this.resgGridAdd.Items.Count;
            }
            List<string> listChecked = GetCheckedItems();

            for (int i = resgGridAdd.CheckedItems.Count - 1; i >= 0; i--)
            {
                var item = resgGridAdd.CheckedItems[i];
                int originalIndex = resgGridAdd.Items.IndexOf(item);
                if((originalIndex + 1) < afterIndex)
                {
                    EIRow row = this.resgGridAdd.EIBlock.Rows[originalIndex];
                    this.resgGridAdd.EIBlock.Rows.RemoveAt(originalIndex);
                    this.resgGridAdd.EIBlock.Rows.Insert(originalIndex + 1, row);
                    afterIndex = originalIndex + 1;

                    //resgGridAdd.CheckAllRows();
                    //for (int j = 0; j < resgGridAdd.EIBlock.Rows.Count; j++)
                    //{
                    //    if (resgGridAdd.EIBlock.Rows[j] != row)
                    //        resgGridAdd.UncheckRow(j);
                    //}
                }
                else
                {
                    afterIndex = originalIndex;
                }
            }

            ReCheckItems(listChecked);
            return;
        }

        private List<string> GetCheckedItems()
        {
            List<string> lstChecked = new List<string>();
            foreach (var item in resgGridAdd.CheckedItems)
            {
                string keyId = Common.GetStringValue(item.GetType().GetProperty("fdKeyId").GetValue(item, null));
                lstChecked.Add(keyId);
            }
            return lstChecked;
        }

        private void ReCheckItems(List<string> lstChecked)
        {
            resgGridAdd.CheckAllRows();
            for (int i = 0; i < resgGridAdd.Items.Count; i++)
            {
                string keyId = Common.GetStringValue(resgGridAdd.Items[i].GetType().GetProperty("fdKeyId").GetValue(resgGridAdd.Items[i], null));

                if (!lstChecked.Contains(keyId))
                {
                    resgGridAdd.UncheckRow(i);
                }
            }
        }

        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            EIInfo info = new EIInfo();
            EIBlock block = this.resgGridAdd.EIBlock;
            info.Attributes[EIConstants.ServiceNameKey] = "ZMCA41";
            info.Attributes[EIConstants.MethodNameKey] = "save";
            info.AddBlock(block);


            EIBlock checkBlock = new EIBlock("checkBlockSave");
            EIColumn column = new EIColumn();
            column.SetName("fdKeyId");
            checkBlock.AddColumn(column);

            checkBlockForSave(produceGroup1, checkBlock);
            checkBlockForSave(produceGroup2, checkBlock);
            checkBlockForSave(securityTrapGroup1, checkBlock);
            checkBlockForSave(securityTrapGroup2, checkBlock);
            checkBlockForSave(securityDisobeyGroup1, checkBlock);
            checkBlockForSave(securityDisobeyGroup2, checkBlock);
            info.AddBlock(checkBlock);
            this.Submit(info, saveCompleted);
        }


        public void checkBlockForSave(SimpleCheckBoxGroup checkBoxGroup, EIBlock block)
        {
            IList<CheckBox> list = checkBoxGroup.checkedItems;
            for (int i = 0; i < list.Count; i++)
            {
                EIRow row = (list[i] as CheckBox).DataContext as EIRow;
                block.AddRow(row);
            }
            return;
        }

        private void saveCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() == -1)
            {
                EFWindow.Alert("数据保存失败！");
                return;
            }
            EFWindow.Alert("数据保存成功！");
            return;
            //if (e.EIInfo.Attributes.ContainsKey("formStatus") && e.EIInfo.Attributes["formStatus"].ToString().Equals("-1"))
            //{
            //    this.resgGridAdd.Refresh();
            //    EFWindow.Alert("数据保存成功！");
            //    return;
            //}
        }
    }
}
